package com.david.IfaceAutoTest.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.david.IfaceAutoTest.domain.InterfaceDomain;
import com.david.IfaceAutoTest.entity.ProjectTokenManagement;
import com.david.IfaceAutoTest.mapper.ProjectTokenManagementMapper;
import com.david.IfaceAutoTest.service.InterfaceService;
import net.sf.json.JSONObject;
import netscape.javascript.JSObject;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 鉴权的接口 Token 获取、自动刷新工具类
 * 动态定时获取并刷新所有项目的token接口，置为全局可用变量。
 *
 * @author david
 * @version 1.0
 * @date 2021/11/2317:05
 */
@Component
@EnableScheduling
@EnableAsync
public class TokenManager {
    @Resource
    ProjectTokenManagementMapper projectTokenManagementMapper;
    @Resource
    InterfaceService interfaceService;
    @Resource
    RedisUtils redisUtils;

    private TokenManager() {

    }

    @Scheduled(cron = "0 */1 * * * ?")
    public void setAllToken() {
        //获取需要跑数的token获取接口列表、解析（解析规则定义）获取token
        //token 命名规则：项目id_token
        // 全局的、支持定时刷新、动态获取  redis
        List<ProjectTokenManagement> projectTokenManagements = projectTokenManagementMapper.selectList(new QueryWrapper<>());
        System.out.println(projectTokenManagements);
        for (ProjectTokenManagement p : projectTokenManagements) {
            Integer interfaceId = p.getTargetInterfaceId();
            Integer projectId = p.getProjectId();
            String tokenFieldName = p.getTokenFieldName();
            String prefix = p.getPrefix()==null?"":p.getPrefix();
            String suffix = p.getSuffix()==null?"":p.getSuffix();
            // todo 层级处理（指定返回结果层级，支持动态解析）---接口返回结果的某对象某字段等。
            String result = interfaceService.getResult(interfaceId);
            JSONObject resultJson = JSONObject.fromObject(result);
            System.out.println(projectId + "_" + tokenFieldName+":-----------"+prefix + resultJson.getString(tokenFieldName) + suffix);
            redisUtils.set(projectId + "_" + tokenFieldName, prefix + resultJson.getString(tokenFieldName) + suffix);
        }
    }




}
